<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button size="small" class="filter-item" style="margin-left: 10px;float:right" type="primary" icon="el-icon-edit"
        @click="handleCreate">添加</el-button>
    </div>

    <el-table v-loading="listLoading" :key="tableKey" :data="list" size="small" border fit highlight-current-row style="width: 100%;margin-top:1%">
      <el-table-column type="index" label="序号">
      </el-table-column>
      <el-table-column label="商品名称" min-width="100px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.seedName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发芽期" min-width="150px" align="center">
        <template slot-scope="scope">

          <img v-if="scope.row.grows[0]" :src="scope.row.grows[0].growthImageUrl" style="width:120px;height:80px" alt="">
        </template>
      </el-table-column>

      <el-table-column label="开花期" min-width="150px" align="center">
        <template slot-scope="scope">
          <img v-if="scope.row.grows[1]" :src="scope.row.grows[1].growthImageUrl" style="width:120px;height:80px" alt="">
        </template>
      </el-table-column>
      <el-table-column label="结果期" min-width="150px" align="center">
        <template slot-scope="scope">
          <img v-if="scope.row.grows[2]" :src="scope.row.grows[2].growthImageUrl" style="width:120px;height:80px" alt="">
        </template>
      </el-table-column>
      <el-table-column label="成熟期" min-width="150px" align="center">
        <template slot-scope="scope">
          <img v-if="scope.row.grows[3]" :src="scope.row.grows[3].growthImageUrl" style="width:120px;height:80px" alt="">
        </template>
      </el-table-column>

      <el-table-column label="果实图片" min-width="150px" align="center">
        <template slot-scope="scope">
          <img v-if="scope.row.feedUrl" :src="scope.row.feedUrl" style="width:120px;height:80px" alt="">
        </template>
      </el-table-column>

      <el-table-column label="种子价格(币/斤)" min-width="100px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.price }}</span>
        </template>
      </el-table-column>
      <el-table-column label="生长周期(天)" min-width="100px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.growthCycle }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最高产量" min-width="100px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.output }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="200px" class-name="small-padding fixed-width">
        <template slot-scope="{ row }">
          <el-button size="small" align="center" type="primary" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="small" align="center" type="primary" @click="handleDel(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize"
      @pagination="getList" />

    <el-dialog :close-on-click-modal="false" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible"
      append-to-body>
      <el-form ref="dataForm" :model="temp" label-position="left" label-width="100px" style="">
        <el-form-item label="商品名称：">
          <el-input v-model="temp.seedName" />
        </el-form-item>
        <el-form-item label="种子价格:">
          <el-input v-model="temp.price" />
        </el-form-item>
        <el-form-item label="生产周期:">
          <el-input v-model="temp.growthCycle" />
        </el-form-item>
        <el-form-item label="每亩产量:">
          <el-input v-model="temp.output" />
        </el-form-item>
        <el-form-item label="果实图片:">
         <el-upload class="avatar-uploader" action="" :show-file-list="false" :on-success="handleAvatarSuccess1"
           :http-request="customRequest1">
           <img style="width:100px;height:100px" v-if="temp.feedUrl" :src="temp.feedUrl" class="avatar">
           <i v-else class="el-icon-plus avatar-uploader-icon"></i>
         </el-upload>
        </el-form-item>

        <p style="font-weight: 700;">农作物生长周期:</p>
        <block v-for='(item,index) in temp.grows' :key="index">
          <el-form-item :label="index==0?'发芽期':index==1?'开花期':index==2?'结果期':'成熟期'">
            <el-row :gutter="20">
              <el-col :span="5">
                <div @click='clickNum(index)'>
                  <el-upload class="avatar-uploader" action="" :show-file-list="false" :on-success="handleAvatarSuccess"
                    :http-request="customRequest">
                    <img style="width:100px;height:100px" v-if="item.growthImageUrl" :src="item.growthImageUrl" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                </div>
              </el-col>
              <el-col :span="3">病害</el-col>
              <el-col :span="5">
                <el-select size="small" placeholder="选择病害" clearable class="filter-item" style="" v-model="item.disaster">
                  <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
                </el-select>
              </el-col>
              <el-col :span="5">
                <el-input size="small" placeholder="平均亩产/斤" v-model="item.reduce" style="" />
              </el-col>
              <el-col :span="5">配置减产数量</el-col>
            </el-row>

          </el-form-item>
        </block>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          返回
        </el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  // 异步请求 delLly
  import {
    getListPage,
    delProinfo,
    updataForm,
    createForm
  } from '@/api/makeMoney/index'

  import {
    listFarmSeed,
    addFarmSeed,
    updateFarmSeed
  } from '../../../../../api/game/farmReq.js'
  import Vue from 'vue'
  import {
    addImg
  } from '@/api/headWheel'
  import {
    parseTime
  } from '@/utils'
  import Pagination from '@/components/Pagination' // 分页插件

  const calendarTypeOptions = [{
      key: 'PETS',
      display_name: '虫灾'
    },
    {
      key: 'DROUGHT',
      display_name: '干旱'
    },
    {
      key: 'LACK',
      display_name: '缺肥'
    }
  ]
  const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
    acc[cur.key] = cur.display_name
    return acc
  }, {})

  export default {
    inject: ["reload"],
    components: {
      Pagination
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          published: 'success',
          draft: 'info',
          deleted: 'danger'
        }
        return statusMap[status]
      },
      typeFilter(type) {
        return calendarTypeKeyValue[type]
      },
    },
    data() {
      return {
        radio: 1,
        sample: [],

        deptValue: '',
        tableKey: 0,
        list: null,
        total: 0,
        listLoading: true,
        listQuery: {
          pageNum: 1,
          pageSize: 10,
          status: '',
          sort: '+id',
        },
        growsIndex:'',
        temp: {
          id: undefined,
          grows: [{
            growthName: "SPROUT",
            sort:1
          }, {
            growthName: "BLOOM",
             sort:2
          }, {
            growthName: "RESULT",
             sort:3
          }, {
            growthName: "RIPE",
             sort:4
          }]
        },
        dialogFormVisible: false,
        calendarTypeOptions,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '添加',
        },
        rowId: "",
        delId: ''
      }
    },
    created() {
      this.getList()
    },
    methods: {
      fabuDate() {
        console.log(this.radio)
        if (this.radio === 1) {
          this.temp.pubTime = '1'
        } else if (this.radio === 2) {
          return this.temp.pubTime
        }
      },

      // 上传周期图片
      handleAvatarSuccess(res, file) {
        this.temp.imgUrl = URL.createObjectURL(file.raw);
      },

      // 选择
      clickNum(index) {
        console.log('index', index)
        this.growsIndex=index
      },
      customRequest(data) {
        const formData = new FormData()
        formData.append('file', data.file)
        this.saveFile(formData)
      },
      saveFile(formData) {
        addImg(formData).then(res => {
          // this.imageUrl=res.data
          this.temp.grows[this.growsIndex].growthImageUrl=res.data.filePath
          console.log(this.temp)
        })
      },


      // 上传果实图片
      handleAvatarSuccess1(res, file) {
        this.temp.imgUrl = URL.createObjectURL(file.raw);
      },

      customRequest1(data) {
        const formData = new FormData()
        formData.append('file', data.file)
        this.saveFile1(formData)
      },
      saveFile1(formData) {
        addImg(formData).then(res => {
          // this.imageUrl=res.data
          this.temp.feedUrl=res.data.filePath
          console.log(this.temp)
        })
      },

      // 查询list
      getList() {
        this.listLoading = true
        var params = Object.assign({}, this.listQuery);
        params.pageNum = this.listQuery.pageNum - 1;

        listFarmSeed(params).then(response => {
          this.list = response.content
          this.total = response.totalElements
          this.listLoading = false
        })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      sortChange(data) {
        const {
          prop,
          order
        } = data
        if (prop === 'id') {
          this.sortByID(order)
        }
      },
      sortByID(order) {
        if (order === 'ascending') {
          this.listQuery.sort = '+id'
        } else {
          this.listQuery.sort = '-id'
        }
        this.handleFilter()
      },
      resetTemp() {
        this.temp = {
          id: undefined,
          grows: [{
            growthName: "SPROUT",
            sort:1
          }, {
            growthName: "BLOOM",
             sort:2
          }, {
            growthName: "RESULT",
             sort:3
          }, {
            growthName: "RIPE",
             sort:4
          }]
        }
      },
      handleUpdate(row) {
        this.temp = Object.assign({}, row) // copy obj
        // this.temp.timestamp = new Date(this.temp.timestamp)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      handleDel(row) {
        let params = Object.assign({}, row) // copy obj
         params.status='0'
        updateFarmSeed(params).then(res => {
          if (res.code === '200') {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }
        })
      },
      updateData() {
        const tempData = Object.assign({}, this.temp)
        console.log('bj',tempData)
        updateFarmSeed(tempData).then(res => {
          // for (const v of this.list) {
          //   if (v.id === this.temp.id) {
          //     const index = this.list.indexOf(v)
          //     this.list.splice(index, 1, this.temp)
          //     break
          //   }
          // }
          this.dialogFormVisible = false
          console.log(res)
          if(res.code=='200'){
            this.$notify({
              title: '成功',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }else{
            this.$notify({
              title: '失败',
              message: res.error_msg,
              type: 'danger',
              duration: 2000
            })
          }

        })

      },
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        console.log(this.temp)
        addFarmSeed(this.temp).then(res => {
          // this.list.unshift(this.temp)
          this.dialogFormVisible = false
          console.log(res)
          if(res.code=='200'){
            this.$notify({
              title: '成功',
              message: '添加成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }else{
            this.$notify({
              title: '失败',
              message: res.error_msg,
              type: 'danger',
              duration: 2000
            })
          }

          // this.$notify({
          //   title: '成功',
          //   message: '添加成功',
          //   type: 'success',
          //   duration: 2000
          // })
          // this.getList()
        })

      },
      getSortClass: function(key) {
        const sort = this.listQuery.sort
        return sort === `+${key}` ?
          'ascending' :
          sort === `-${key}` ?
          'descending' :
          ''
      }
    }
  }
</script>
<style scoped>
  .avatar-uploader>>> .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }

  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
</style>
